package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 远程调用dubbo服务，返回mybatis-plus的分页对象
        IPage<UserInfo> iPage = userInfoApi.findByPage(page, pagesize);
        // 构造返回给前端的分页数据
        PageResult pageResult =
                new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> findVideoList(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = videoApi.findByPage(page, pagesize, uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();

        //2、创建返回的vo集合对象
        List<VideoVo> voList = new ArrayList<>();

        //3. 封装数据
        if (videoList != null) {
            for (Video video : videoList) {
                //3.1 创建vo对象，封装前端返回的数据
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(video, vo);
                //3.2 根据用户id查询用户并封装
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                //3.3 设置小视频封面
                vo.setCover(video.getPicUrl());
                //3.4 设置id、签名
                vo.setId(video.getId().toString());
                vo.setSignature(video.getText());
                vo.setHasLiked(0);

                //3.5 vo添加到集合
                voList.add(vo);
            }
        }
        //4. 设置到PageResult中
        pageResult.setItems(voList);

        //5. 响应
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> findMovementsList(
            Integer page, Integer pagesize, Long uid, Integer state) {
        PageResult pageResult = publishApi.queryPublishList(page, pagesize,uid,state);
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        //3. 封装返回的结果MovementsVo集合
        //3.1 创建返回结果
        List<MovementsVo> voList = new ArrayList<>();
        //3.2 遍历查询的发布动态集合
        if (CollectionUtils.isNotEmpty(publishList)) {
          voList = publishList.stream().map(publish -> {

                  //3.2.1 创建vo对象
                  MovementsVo vo = new MovementsVo();
                  //3.2.2 封装数据：发布动态
                  BeanUtils.copyProperties(publish, vo);
                  //3.2.3 封装数据：先查询用户详情，再封装
                  UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                  if (userInfo != null) {
                      BeanUtils.copyProperties(userInfo, vo);
                      if (userInfo.getTags() != null) {
                          vo.setTags(userInfo.getTags().split(","));
                      }
                  }
                  //3.2.3 封装数据：其他参数
                  vo.setId(publish.getId().toString());
                  vo.setUserId(publish.getUserId());
                  vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                  vo.setDistance("50米");
                  vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

                  //3.2.4 对象添加到集合
              return vo;
          }).collect(Collectors.toList());
        }

        //4. 在把封装好的vo集合设置到分页对象中
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：动态详情
     */
    public ResponseEntity<Object> findMovementsById(String publishId) {
        Publish publish = publishApi.findById(publishId);

        //3.2.1 创建vo对象
        MovementsVo vo = new MovementsVo();
        //3.2.2 封装数据：发布动态
        BeanUtils.copyProperties(publish, vo);
        //3.2.3 封装数据：先查询用户详情，再封装
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        //3.2.3 封装数据：其他参数
        vo.setId(publish.getId().toString());
        vo.setUserId(publish.getUserId());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("50米");
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        //1. 根据动态id分页查询评论
        PageResult pageResult = commentApi.queryCommentsList(publishId,page,pagesize);

        //2. 获取查询数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        //3. 创建返回的vo集合数据
        List<CommentVo> voList = new ArrayList<>();

        //4. 封装voList
        if (commentList != null) {
            for (Comment comment : commentList) {
                CommentVo vo = new CommentVo();
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo,vo);
                }
                vo.setId(comment.getId().toString());

                vo.setContent(comment.getContent());
                vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                vo.setLikeCount(0);
                vo.setHasLiked(0);

                voList.add(vo);
            }
        }

        //5. 设置到分页对象中并返回
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     *动态 通过
     * @param
     * @return
     */
    public ResponseEntity<Object> queryPassList(List<String> publishId) {

        boolean queryPass =publishApi.queryPassList(publishId);
        String message = "操作失败";
        if (queryPass){
            message="操作成功";
        }
        return ResponseEntity.ok(message);
    }
    /**
     *动态 拒绝
     * @param
     * @return
     */
    public ResponseEntity<Object> queryReject(List<String> publishId) {
        boolean queryReject = publishApi.queryReject(publishId);
        String message = "拒绝失败";
        if (queryReject){
            message = "拒绝成功";
        }
        return ResponseEntity.ok((queryReject));
    }
}
